package org.demo6;

import org.springframework.batch.core.*;
import org.springframework.batch.core.launch.*;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("demo6/demo6-job.xml");
        Job job = (Job) context.getBean("chunkJob");
        JobLauncher launcher = (JobLauncher) context.getBean("jobLauncher");
        JobOperator jobOperator = (JobOperator) context.getBean("jobOperator");
        try {
            JobExecution result = launcher.run(job, new JobParametersBuilder().addDate("date",new Date()).toJobParameters());
            Set<Long> longs = jobOperator.getRunningExecutions("chunkJob");
            Iterator<Long> iterator = longs.iterator();
            while (iterator.hasNext()) {
                boolean sendMessage = jobOperator.stop(iterator.next());
                System.out.println("sendMessage" + sendMessage);
            }
        } catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException |
                 JobParametersInvalidException | NoSuchJobException | NoSuchJobExecutionException |
                 JobExecutionNotRunningException e) {
            throw new RuntimeException(e);
        }
    }
}
